package com.funcourse.demo.business.conf;

import com.funcourse.demo.business.CompeteRoomService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class RedisKeyExpirationListener implements MessageListener {

  @Autowired
  CompeteRoomService competeRoomService;


  @Autowired
  RedisTemplate redisTemplate;

  /**
   * refer to RoomCacher.ROOM_KEY_SHADOW_PREFIX
   */
  private static final Pattern ROOM_SHADOW_KEY_PATTERN = Pattern.compile("funcourse\\.room\\.shadow\\.realtime\\.(.{24})");

  @Override
  public void onMessage(Message message, byte[] bytes) {
    String key = new String(message.getBody());
    final Matcher matcher = ROOM_SHADOW_KEY_PATTERN
        .matcher(key);
    if(matcher.matches()){
      log.info("room closed after expire: {}", key);
      competeRoomService.closeRealTimeRoom(matcher.group(1),false);
    }

  }
}
